package io.renren.common.utils;

import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;


/**
 * 实现GET以及POST请求
 */
public class UrlReqUtil {

    /**
     * 小程序图片保存路径
     * 路径在WebConfig.java文件中配置，
     * registry.addResourceHandler("/img/**").addResourceLocations("file:D:\\IDEAWorkSpace\\renren-security\\renren-api\\src\\main\\resources\\static\\img\\");
     * addResourceHandler设置的是请求路径，addResourceLocations设置的是请求路径映射的资源文件位置
     */
    //todo 正式环境中需要改为应用服务器的地址和对应的图片保存路径
    public static final String IMG_SAVE_PATH = "C:\\img\\";
    public static final String VIDEO_SAVE_PATH = "C:\\video\\";
    public static final String IMG_REQUEST_PATH = "http://localhost:8081/renren-api/img/";
    public static final String VIDEO_REQUEST_PATH = "http://localhost:8081/renren-api/video/";


    public static JSONObject get(String url) {
        HttpURLConnection http = null;
        InputStream is = null;
        try {
            URL urlGet = new URL(url);
            http = (HttpURLConnection) urlGet.openConnection();
            http.setRequestMethod("GET");
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
            System.setProperty("sun.net.client.defaultReadTimeout", "30000");
            http.connect();
            is = http.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            String message = new String(jsonBytes, "UTF-8");
            return JSONObject.fromObject(message);
        } catch (Exception e) {
            return null;
        } finally {
            if (null != http) {
                http.disconnect();
            }
            try {
                if (null != is) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String post(String url, String data) {
        HttpURLConnection http = null;
        PrintWriter out = null;
        BufferedReader reader = null;
        try {
            //创建连接
            URL urlPost = new URL(url);
            http = (HttpURLConnection) urlPost.openConnection();
            http.setDoOutput(true);
            http.setDoInput(true);
            http.setRequestMethod("POST");
            http.setUseCaches(false);
            http.setInstanceFollowRedirects(true);
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.connect();
            //POST请求
            OutputStreamWriter outWriter = new OutputStreamWriter(http.getOutputStream(), "utf-8");
            out = new PrintWriter(outWriter);
            out.print(data);
            out.flush();
            out.close();
            out = null;
            //读取响应
            reader = new BufferedReader(new InputStreamReader(http.getInputStream()));
            String lines;
            StringBuffer sb = new StringBuffer("");
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), "utf-8");
                sb.append(lines);
            }
            reader.close();
            reader = null;
            System.out.println(sb.toString());
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (null != http) {
                http.disconnect();
            }
            if (null != out) {
                out.close();
            }
            try {
                if (null != reader) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String createPETAQRCode(String url, String data) {
        HttpURLConnection http = null;
        PrintWriter out = null;
        BufferedReader reader = null;
        String fileName = RandomUtil.generateString(16);
        try {
            //创建连接
            URL urlPost = new URL(url);
            http = (HttpURLConnection) urlPost.openConnection();
            http.setDoOutput(true);
            http.setDoInput(true);
            http.setRequestMethod("POST");
            http.setUseCaches(false);
            http.setInstanceFollowRedirects(true);
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.connect();
            //POST请求
            OutputStreamWriter outWriter = new OutputStreamWriter(http.getOutputStream(), "utf-8");
            out = new PrintWriter(outWriter);
            out.print(data);
            out.flush();
            out.close();
            out = null;
            //读取响应
            InputStream fis = http.getInputStream();
            //可以是任何图片格式.jpg,.png等
            File file = new File(UrlReqUtil.IMG_SAVE_PATH + fileName + ".jpg");
            FileOutputStream fos = new FileOutputStream(file);
            byte[] b = new byte[1024];
            int nRead = 0;
            while ((nRead = fis.read(b)) != -1) {
                fos.write(b, 0, nRead);
            }
            fos.flush();
            fos.close();
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (null != http) {
                http.disconnect();
            }
            if (null != out) {
                out.close();
            }
            try {
                if (null != reader) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return UrlReqUtil.IMG_REQUEST_PATH + fileName + ".jpg";
    }

    /**
     * 判断请求中是否含有图片文件，如果有则保存到本地后返回对应图片的外部访问路径
     *
     * @param request
     * @return
     * @throws IOException
     */
    public static String isContainsIMG(HttpServletRequest request) throws IOException {
        String imgURL = null;
        if (request instanceof MultipartHttpServletRequest) {
            String sn = RandomUtil.generateString(16);
            MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
            MultipartFile multipartFile = req.getFile("file");
            File dir = new File(IMG_SAVE_PATH);
            if (!dir.exists()) {
                dir.mkdir();
            }
            File file = new File(IMG_SAVE_PATH, sn + ".jpg");
            multipartFile.transferTo(file);
            imgURL = IMG_REQUEST_PATH + sn + ".jpg";
            System.out.println("IMG_REQUEST_PATH========="+IMG_REQUEST_PATH);
        }
        return imgURL;
    }

    /**
     * 上传视频
     *
     * @param request
     * @return
     * @throws IOException
     */
    public static String isContainsVideo(HttpServletRequest request) throws IOException {
        String imgURL = null;
        if (request instanceof MultipartHttpServletRequest) {
            String sn = RandomUtil.generateString(16);
            MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
            MultipartFile multipartFile = req.getFile("file");
            File dir = new File(VIDEO_SAVE_PATH);
            if (!dir.exists()) {
                dir.mkdir();
            }
            String fileName = multipartFile.getOriginalFilename();
            String fileTyle=fileName.substring(fileName.lastIndexOf("."),fileName.length());
            File file = new File(VIDEO_SAVE_PATH, sn +fileTyle);
            multipartFile.transferTo(file);
            imgURL = VIDEO_REQUEST_PATH + sn + fileTyle;
        }
        return imgURL;
    }

    /**
     * 批量上传图片处理
     *
     * @param request
     * @return
     * @throws IOException
     */
    public static List isContainsIMGS(HttpServletRequest request) throws IOException {
        List<String> list = new ArrayList<>();
        if (request instanceof MultipartHttpServletRequest) {
            String sn = RandomUtil.generateString(16);
            MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
            MultipartFile multipartFile = req.getFile("file");
            File dir = new File(IMG_SAVE_PATH);
            if (!dir.exists()) {
                dir.mkdir();
            }
            File file = new File(IMG_SAVE_PATH, sn + ".jpg");
            multipartFile.transferTo(file);
            String imgURL = IMG_REQUEST_PATH + sn + ".jpg";
            list.add(imgURL);
        }
        return list;
    }

    /**
     * 字符串转二进制
     *
     * @param str 要转换的字符串
     * @return 转换后的二进制数组
     */
    public static byte[] hex2byte(String str) { // 字符串转二进制
        if (str == null) {
            return null;
        }
        str = str.trim();
        int len = str.length();
        if (len == 0 || len % 2 == 1) {
            return null;
        }
        byte[] b = new byte[len / 2];
        try {
            for (int i = 0; i < str.length(); i += 2) {
                b[i / 2] = (byte) Integer
                        .decode("0X" + str.substring(i, i + 2)).intValue();
            }
            return b;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 二进制转字符串
     *
     * @param b
     * @return
     */
    public static String byte2hex(byte[] b) // 二进制转字符串
    {
        StringBuffer sb = new StringBuffer();
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1) {
                sb.append("0" + stmp);
            } else {
                sb.append(stmp);
            }

        }
        return sb.toString();
    }

    public static int saveToImgByBytes(File imgFile, String imgPath, String imgName) {

        int stateInt = 1;
        if (imgFile.length() > 0) {
            try {
                File file = new File(imgPath, imgName);//可以是任何图片格式.jpg,.png等
                FileOutputStream fos = new FileOutputStream(file);

                FileInputStream fis = new FileInputStream(imgFile);

                byte[] b = new byte[1024];
                int nRead = 0;
                while ((nRead = fis.read(b)) != -1) {
                    fos.write(b, 0, nRead);
                }
                fos.flush();
                fos.close();
                fis.close();

            } catch (Exception e) {
                stateInt = 0;
                e.printStackTrace();
            } finally {
            }
        }
        return stateInt;
    }


    @Value("${imgs.localhost}")
    private static String imgs;

    public static String PictureUploading(MultipartFile file, String newName) {
        // 获取文件名
        String fileName = file.getOriginalFilename();
        //logger.info("上传的文件名为：" + fileName);
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //logger.info("上传的后缀名为：" + suffixName);
        // 文件上传后的路径
        //String filePath = "C://test//";

        //生成随机名字
        //String newName = RandomUtil.generateString(12);

        // 解决中文问题，liunx下中文路径，图片显示问题
        // fileName = UUID.randomUUID() + suffixName;
        File dest = new File(imgs + newName);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            //return "上传成功";
            return "true";
        } catch (IllegalStateException e) {
            return e.getMessage();
        } catch (IOException e) {
            return e.getMessage();
        }
        //return "上传图片异常";
    }

}